<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(A卷,200分)- 最大化控制资源成本（Java & JS & Python）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>公司创新实验室正在研究如何最小化资源成本&#xff0c;最大化资源利用率&#xff0c;请你设计算法帮他们解决一个任务混部问题&#xff1a;</p> 
<p>有taskNum项任务&#xff0c;每个任务有开始时间&#xff08;startTime&#xff09;&#xff0c;结束时间&#xff08;endTime&#xff09;&#xff0c;并行度&#xff08;parallelism&#xff09;三个属性&#xff0c;</p> 
<p>并行度是指这个任务运行时将会占用的服务器数量&#xff0c;一个服务器在每个时刻可以被任意任务使用但最多被一个任务占用&#xff0c;任务运行完成立即释放&#xff08;结束时刻不占用&#xff09;。</p> 
<p>任务混部问题是指给定一批任务&#xff0c;让这批任务由同一批服务器承载运行&#xff0c;</p> 
<p>请你计算完成这批任务混部最少需要多少服务器&#xff0c;从而最大化控制资源成本。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>第一行输入为taskNum&#xff0c;表示有taskNum项任务<br /> 接下来taskNum行&#xff0c;每行三个整数&#xff0c;表示每个任务的</p> 
<p>开始时间&#xff08;startTime &#xff09;&#xff0c;结束时间&#xff08;endTime &#xff09;&#xff0c;并行度&#xff08;parallelism&#xff09;</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>一个整数&#xff0c;表示最少需要的服务器数量</p> 
<p></p> 
<h4>备注</h4> 
<ul><li><code>1 &lt;&#61; taskNum &lt;&#61; 100000</code></li><li><code>0 &lt;&#61; startTime &lt; endTime &lt;&#61; 50000</code></li><li><code>1 &lt;&#61; parallelism &lt;&#61; 100</code></li></ul> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">3<br /> 2 3 1<br /> 6 9 2<br /> 0 5 1</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">2</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;"> <p>一共有三个任务&#xff0c;</p> <p>第一个任务在时间区间[2, 3]运行&#xff0c;占用1个服务器&#xff0c;<br /> 第二个任务在时间区间[6, 9]运行&#xff0c;占用2个服务器&#xff0c;<br /> 第三个任务在时间区间[0, 5]运行&#xff0c;占用1个服务器&#xff0c;<br /> 需要最多服务器的时间区间为[2, 3]和[6, 9]&#xff0c;需要2个服务器。</p> </td></tr></tbody></table> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">2<br /> 3 9 2<br /> 4 7 3</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">5</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;"> <p>一共两个任务&#xff0c;</p> <p>第一个任务在时间区间[3, 9]运行&#xff0c;占用2个服务器&#xff0c;<br /> 第二个任务在时间区间[4, 7]运行&#xff0c;占用3个服务器&#xff0c;<br /> 需要最多服务器的时间区间为[4, 7]&#xff0c;需要5个服务器。</p> </td></tr></tbody></table> 
<h4></h4> 
<h3 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">最大区间重叠个数求解</h3> 
<p>本题可以用求解最大区间重叠个数的方式求解。</p> 
<p>关于最大重叠区间个数求解&#xff0c;请看<a href="https://www.bilibili.com/video/BV1nq4y1B7Mm/?vd_source&#61;b5105a99a0628dd906e154263279c518" rel="nofollow" title="年年岁岁都容易挂的算法高频面试题&#xff0c;一线大厂经典面试题之堆和最大线段重合问题_哔哩哔哩_bilibili">年年岁岁都容易挂的算法高频面试题&#xff0c;一线大厂经典面试题之堆和最大线段重合问题_哔哩哔哩_bilibili</a></p> 
<p>上面视频的核心思想其实就是&#xff1a;</p> 
<ul><li>首先&#xff0c;将所有区间按开始位置升序</li><li>然后&#xff0c;遍历排序后区间&#xff0c;并将小顶堆中小于遍历区间起始位置的区间弹出&#xff08;小顶堆实际存储区间结束位置&#xff09;&#xff0c;此操作后&#xff0c;小顶堆中剩余的区间个数&#xff0c;就是和当前遍历区间重叠数。</li></ul> 
<p>我们只需要在求解最大重叠数时&#xff0c;保留遍历的区间的起始位置即可。</p> 
<p></p> 
<p>但是本题并不是要求解最大区间重叠个数&#xff0c;而是要求解重叠区间的权重和。因此&#xff0c;我们需要定义一个变量sum来记录重叠区间的权重和&#xff0c;当小顶堆弹出不重叠区间时&#xff0c;sum需要减去被弹出区间的权重&#xff0c;当我们向小顶堆压入重叠区间时&#xff0c;则sum需要加上被压入区间的权重。</p> 
<p></p> 
<h4>JavaScript算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
let n;
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61;&#61; 1) {
    n &#61; lines[0] - 0;
  }

  if (n &amp;&amp; lines.length &#61;&#61;&#61; n &#43; 1) {
    const ranges &#61; lines.slice(1).map((line) &#61;&gt; line.split(&#34; &#34;).map(Number));
    console.log(getResult(ranges));
    lines.length &#61; 0;
  }
});

function getResult(ranges) {
  ranges.sort((a, b) &#61;&gt; a[0] - b[0]);
  const end &#61; new PriorityQueue((a, b) &#61;&gt; b[0] - a[0]);

  let max &#61; 0;
  let sum &#61; 0;
  for (let range of ranges) {
    const [s, e, p] &#61; range;

    while (end.size()) {
      const top &#61; end.peek();

      if (top[0] &lt;&#61; s) {
        const poll &#61; end.shift();
        sum -&#61; poll[1];
      } else {
        break;
      }
    }

    end.push([e, p]);
    sum &#43;&#61; p;

    if (sum &gt; max) {
      max &#61; sum;
    }
  }

  return max;
}

class PriorityQueue {
  constructor(cpr) {
    this.queue &#61; [];
    this.cpr &#61; cpr;
  }

  swap(a, b) {
    const tmp &#61; this.queue[a];
    this.queue[a] &#61; this.queue[b];
    this.queue[b] &#61; tmp;
  }

  // 上浮
  swim() {
    let c &#61; this.queue.length - 1;

    while (c &gt;&#61; 1) {
      const f &#61; Math.floor((c - 1) / 2);

      if (this.cpr(this.queue[c], this.queue[f]) &gt; 0) {
        this.swap(c, f);
        c &#61; f;
      } else {
        break;
      }
    }
  }

  // 入队
  push(val) {
    this.queue.push(val);
    this.swim();
  }

  // 下沉
  sink() {
    let f &#61; 0;

    while (true) {
      let c1 &#61; 2 * f &#43; 1;
      let c2 &#61; c1 &#43; 1;

      let c;
      let val1 &#61; this.queue[c1];
      let val2 &#61; this.queue[c2];
      if (val1 &amp;&amp; val2) {
        c &#61; this.cpr(val1, val2) &gt; 0 ? c1 : c2;
      } else if (val1 &amp;&amp; !val2) {
        c &#61; c1;
      } else if (!val1 &amp;&amp; val2) {
        c &#61; c2;
      } else {
        break;
      }

      if (this.cpr(this.queue[c], this.queue[f]) &gt; 0) {
        this.swap(c, f);
        f &#61; c;
      } else {
        break;
      }
    }
  }

  // 出队
  shift() {
    this.swap(0, this.queue.length - 1);
    const res &#61; this.queue.pop();
    this.sink();
    return res;
  }

  // 查看顶
  peek() {
    return this.queue[0];
  }

  size() {
    return this.queue.length;
  }
}
</code></pre> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    int n &#61; sc.nextInt();

    int[][] ranges &#61; new int[n][3];

    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      ranges[i][0] &#61; sc.nextInt();
      ranges[i][1] &#61; sc.nextInt();
      ranges[i][2] &#61; sc.nextInt();
    }

    System.out.println(getResult(ranges));
  }

  public static int getResult(int[][] ranges) {
    Arrays.sort(ranges, (a, b) -&gt; a[0] - b[0]);

    PriorityQueue&lt;Integer[]&gt; end &#61; new PriorityQueue&lt;&gt;((a, b) -&gt; a[0] - b[0]);

    int max &#61; 0;
    int sum &#61; 0;
    for (int[] range : ranges) {
      int s &#61; range[0];
      int e &#61; range[1];
      int p &#61; range[2];

      while (end.size() &gt; 0) {
        Integer[] top &#61; end.peek();

        if (top[0] &lt;&#61; s) {
          Integer[] poll &#61; end.poll();
          sum -&#61; poll[1];
        } else {
          break;
        }
      }

      end.offer(new Integer[] {e, p});
      sum &#43;&#61; p;

      if (sum &gt; max) {
        max &#61; sum;
      }
    }
    return max;
  }
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python">import queue

# 输入获取
taskNum &#61; int(input())
ranges &#61; [list(map(int, input().split())) for i in range(taskNum)]


# 算法入口
def getResult(ranges):
    ranges.sort(key&#61;lambda x: x[0])
    end &#61; queue.PriorityQueue()
    maxV &#61; 0
    sum &#61; 0

    for ran in ranges:
        s, e, p &#61; ran

        while end.qsize() &gt; 0:
            top &#61; end.queue[0]

            if top[0] &lt;&#61; s:
                poll &#61; end.get()
                sum -&#61; poll[1]
            else:
                break

        end.put((e, p))
        sum &#43;&#61; p

        if sum &gt; maxV:
            maxV &#61; sum

    return maxV


# 算法调用
print(getResult(ranges))
</code></pre> 
<p></p> 
<p></p> 
<h3>差分数列求解</h3> 
<p>当我们要给区间的某个范围的每个元素加上相同的增量时&#xff0c;此时最简单的方法就是先求解对应区间的差分数列&#xff0c;然后在差分数列对应范围的左右边界上做处理。具体请看&#xff1a;</p> 
<p><a href="https://fcqian.blog.csdn.net/article/details/128976936" rel="nofollow" title="算法设计 - 前缀和 &amp; 差分数列_伏城之外的博客-CSDN博客">算法设计 - 前缀和 &amp; 差分数列_伏城之外的博客-CSDN博客</a></p> 
<p> </p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    int n &#61; sc.nextInt();

    int[][] ranges &#61; new int[n][3];

    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      ranges[i][0] &#61; sc.nextInt();
      ranges[i][1] &#61; sc.nextInt();
      ranges[i][2] &#61; sc.nextInt();
    }

    System.out.println(getResult(ranges));
  }

  public static int getResult(int[][] ranges) {
    int[] arr &#61; new int[50000];

    for (int[] range : ranges) {
      int start &#61; range[0];
      int end &#61; range[1];
      int diff &#61; range[2];

      arr[start] &#43;&#61; diff;
      // 结束时刻不占用&#xff0c;因此不需要end&#43;1
      arr[end] -&#61; diff;
    }

    int ans &#61; arr[0];

    // 求解差分数列的前缀和
    for (int i &#61; 1; i &lt; arr.length; i&#43;&#43;) {
      arr[i] &#43;&#61; arr[i - 1];
      ans &#61; Math.max(ans, arr[i]);
    }

    return ans;
  }
}
</code></pre> 
<h4>JavaScript算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
let n;
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61;&#61; 1) {
    n &#61; lines[0] - 0;
  }

  if (n &amp;&amp; lines.length &#61;&#61;&#61; n &#43; 1) {
    const ranges &#61; lines.slice(1).map((line) &#61;&gt; line.split(&#34; &#34;).map(Number));
    console.log(getResult(ranges));
    lines.length &#61; 0;
  }
});

function getResult(ranges) {
  const arr &#61; new Array(50000).fill(0);

  for (let [start, end, diff] of ranges) {
    arr[start] &#43;&#61; diff;
    // 结束时刻不占用&#xff0c;因此不需要end&#43;1
    arr[end] -&#61; diff;
  }

  // 求解差分数列的前缀和
  let ans &#61; arr[0];
  for (let i &#61; 1; i &lt; arr.length; i&#43;&#43;) {
    arr[i] &#43;&#61; arr[i - 1];
    ans &#61; Math.max(ans, arr[i]);
  }

  return ans;
}
</code></pre> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
taskNum &#61; int(input())
ranges &#61; [list(map(int, input().split())) for i in range(taskNum)]


# 算法入口
def getResult(ranges):
    arr &#61; [0]*50000

    for start, end, diff in ranges:
        arr[start] &#43;&#61; diff
        # 结束时刻不占用&#xff0c;因此不需要end&#43;1
        arr[end] -&#61; diff

    ans &#61; arr[0]
    # 求解差分数列的前缀和
    for i in range(1, 50000):
        arr[i] &#43;&#61; arr[i-1]
        ans &#61; max(ans, arr[i])

    return ans


# 算法调用
print(getResult(ranges))
</code></pre>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>